// import React, { Component } from 'react';
// import {
//   StyleSheet, View, FlatList, Text, DeviceEventEmitter,
// } from 'react-native';
// import produce from 'immer';
// import { Icon } from 'native-base';
// import Item from './item';
// import Tab from '../tab';
// import {
//   ListFooter, BlankBackground, Loading,
// } from '../../../components';
// import * as todoService from '../../../services/todo';

// class DevicesList extends Component {
//   page = 1; // 分页请求的当前页数

//   startPosition = 0; // 开始滑动的位置

//   index = 0; // 记录当前page的index

//   constructor(props) {
//     super(props);
//     this.state = {
//       list: [],
//       refreshing: false,
//       isMore: false,
//       isError: false,
//       showLoading: true,
//     };
//   }

//   componentDidMount() {
//     this._onInitRefresh();
//   }

//   fetchList = async (payload) => {
//     try {
//       this.setState({ isError: false });
//       const currPage = this.page + 1;
//       const { list, page, total } = await todoService.search({ ...payload, page: currPage });

//       this.setState(produce(draft => {
//         // eslint-disable-next-line no-restricted-syntax
//         draft.list.push(...list);
//         this.page = page;
//         draft.isMore = draft.list.length < total;
//       }));
//     } catch (error) {
//       this.setState({ isError: true });
//     }
//   }

//   refresh = async (payload) => {
//     try {
//       this.setState({ isError: false });
//       const { list, page, total } = await todoService.search({ ...payload, page: 1 });
//       const isMore = list.length < total;
//       this.setState(produce(draft => {
//         // eslint-disable-next-line no-restricted-syntax
//         draft.list.push(...list);
//         draft.refreshing = false;
//         this.page = page;
//         draft.isMore = isMore;
//       }));
//     } catch (error) {
//       this.setState({ isError: true, refreshing: false });
//     }
//   }

//   initRefreshList = async (payload) => {
//     try {
//       this.setState({ showLoading: true, isError: false, list: [] });
//       const { list, page, total } = await todoService.search({ ...payload, page: 1 });
//       const isMore = list.length < total;
//       this.setState(produce(draft => {
//         draft.list = list;
//         draft.showLoading = false;
//         this.page = page;
//         draft.isMore = isMore;
//       }));
//     } catch (error) {
//       this.setState({ isError: true, showLoading: false });
//     }
//   }

//   // 刷新时候获取数据
//   _onRefresh = () => {
//     this.refreshList({ status: 0, title: 1, type: 1 });
//   }

//   // 初始化的时候获取数据
//   _onInitRefresh = () => {
//     this.initRefreshList({ status: 0, title: 1, type: 1 });
//   }

//   // 上拉加载数据
//   _onEndReached = () => {
//     if (this.state.isMore) {
//       this.fetchList({ status: 0, title: 1, type: 1 });
//     }
//   }

//   _onItemClick = (item) => {
//     global.navigation.navigate({ routeName: 'About', params: { id: item._id } });
//   }

//   // 列表的item组件
//   _renderItem = (item) => (<Item msgItem={item.item} onItemClick={this._onItemClick} />);

//   // 列表的分割线
//   _renderItemSeparator = () => (
//     <View style={{ height: 0.5, backgroundColor: '#EDF5FA' }} />
//   )

//   // 列表上拉加载的组件
//   _renderListFooter = () => (
//     (this.state.list.length > 0) && <ListFooter isMore={this.state.isMore} />
//   );

//   _onScrollStart = (event) => {
//     this.startPosition = event.nativeEvent.contentOffset.y;
//   }

//   _onScrollEnd = (event) => {
//     const distance = event.nativeEvent.contentOffset.y - this.startPosition;
//     if (distance > 100) {
//       if (this._FlatList) {
//         if (this.index < this.state.list.length - 1) {
//           this.index = this.index + 1;
//           this._FlatList.scrollToIndex({ viewPosition: 0, index: this.index });
//         }
//       }
//     } else if (distance < -100) {
//       if (this._FlatList) {
//         if (this.index > 0) {
//           this.index = this.index - 1;
//           this._FlatList.scrollToIndex({ viewPosition: 0, index: this.index });
//         }
//       }
//     } else {
//       this._FlatList.scrollToIndex({ viewPosition: 0, index: this.index });
//     }
//   }

//   toIncident = () => {
//     DeviceEventEmitter.emit('changePageIndexEvent', 'incident');
//   }

//   toQrcode = () => {
//     global.navigation.navigate({ routeName: 'Qrcode' });
//   }

//   toSearch = () => {
//     DeviceEventEmitter.emit('swiperIncidentPageEvent', -1);
//   }

//   _FlatList;

//   render() {
//     const {
//       showLoading, isError, list, refreshing,
//     } = this.state;

//     let mView = <Loading />;
//     if (!showLoading) {
//       if (list.length === 0) {
//         mView = <BlankBackground isError={isError} onRefresh={this._onInitRefresh} />;
//       } else {
//         mView = (
//           <FlatList
//             ref={(ref) => {
//               this._FlatList = ref;
//             }}
//             renderItem={this._renderItem}
//             data={list}
//             keyExtractor={(item, index) => item + index}
//             onRefresh={this._onRefresh}
//             refreshing={refreshing}
//             onEndReachedThreshold={0.05}
//             onScrollBeginDrag={this._onScrollStart}
//             onScrollEndDrag={this._onScrollEnd}
//             scrollEventThrottle={200}
//             onEndReached={this._onEndReached}
//             ListFooterComponent={this._renderListFooter}
//             // ItemSeparatorComponent={this._renderItemSeparator}
//           />
//         );
//       }
//     }

//     return (
//       <View style={styles.container}>
//         <View style={styles.header}>
//           <Icon
//             onPress={this.toSearch}
//             type="MaterialIcons"
//             name="search"
//             style={styles.icon}
//           />
//           <View style={{ flexDirection: 'row', justifyContent: 'center', alignItems: 'center' }}>
//             <Text onPress={this.toIncident} style={{ color: 'white', fontSize: 17 }}>故障 | </Text>
//             <Text style={{ color: 'white', fontWeight: 'bold', fontSize: 18 }}>设备</Text>
//           </View>
//           <Icon
//             onPress={this.toQrcode}
//             type="MaterialCommunityIcons"
//             name="qrcode"
//             style={styles.icon}
//           />
//         </View>
//         <Tab />
//         {mView}

//       </View>
//     );
//   }
// }

// const styles = StyleSheet.create({
//   container: {
//     flex: 1,
//     width: '100%',
//     backgroundColor: 'black',
//   },
//   header: {
//     position: 'absolute',
//     flexDirection: 'row',
//     justifyContent: 'space-between',
//     alignItems: 'center',
//     backgroundColor: 'rgba(0,0,0,0.5)',
//     width: '100%',
//     height: 48,
//     zIndex: 1,
//   },
//   footer: {
//     bottom: 0,
//     position: 'absolute',
//     flexDirection: 'row',
//     justifyContent: 'space-between',
//     alignItems: 'center',
//     backgroundColor: 'rgba(0,0,0,0.5)',
//     width: '100%',
//     height: 48,
//     zIndex: 1,
//   },
//   icon_container: {
//     flex: 1,
//     justifyContent: 'center',
//     alignItems: 'center',
//   },
//   icon: {
//     color: 'white',
//     padding: 10,
//   },
// });

// export default DevicesList;


import React, { Component } from 'react';
import {
  StyleSheet, View, FlatList, Text, DeviceEventEmitter, TouchableWithoutFeedback, Image,
} from 'react-native';
import { Icon } from 'native-base';
import produce from 'immer';
import Item from './item';
import Tab from '../tab';
import {
  ListFooter, BlankBackground, Loading,
} from '../../../components';
import * as todoService from '../../../services/todo';
import ZlstIcon from '../../../components/zlst-icons';
import Theme from '../../../native-base-theme/variables/commonColor';

class DevicesList extends Component {
  page = 1; // 分页请求的当前页数

  startPosition = 0; // 开始滑动的位置

  index = 0; // 记录当前page的index

  constructor(props) {
    super(props);
    this.state = {
      list: [],
      refreshing: false,
      isMore: false,
      isError: false,
      showLoading: true,
      total: 0,
      index: 0,
      showIncidentBadge: false,
      choice: 'all',
    };
  }

  componentDidMount() {
    this._onInitRefresh();
    DeviceEventEmitter.addListener('refreshPageEvent', this.refreshPageEvent);
  }

  componentWillUnmount() {
    DeviceEventEmitter.removeAllListeners('refreshPageEvent');
  }

  refreshPageEvent = () => {
    this.index = 0;
    this._onInitRefresh();
  }

  fetchList = async (payload) => {
    try {
      this.setState({ isError: false });
      const currPage = this.page + 1;
      const { list, page, total } = await todoService.queryEquipmentByparams({ page: currPage, isHomeQueryFlag: true });
      this.setState(produce(draft => {
        // eslint-disable-next-line no-restricted-syntax
        draft.list.push(...list);
        this.page = page;
        draft.isMore = draft.list.length < total;
        draft.total = total;
      }));
    } catch (error) {
      this.setState({ isError: true });
    }
  }

  refreshList = async (payload) => {
    try {
      this.setState({ isError: false });
      const { list, page, total } = await todoService.queryEquipmentByparams({ page: 1, isHomeQueryFlag: true });
      const isMore = list.length < total;
      this.setState(produce(draft => {
        // eslint-disable-next-line no-restricted-syntax
        draft.list = list;
        draft.refreshing = false;
        this.page = page;
        draft.isMore = isMore;
        draft.total = total;
        if (list.length > 0 && list[0].status == 2) {
          draft.showIncidentBadge = true;
        }
      }));
    } catch (error) {
      this.setState({ isError: true, refreshing: false });
    }
  }

  initRefreshList = async (payload) => {
    try {
      this.setState({ showLoading: true, isError: false, list: [] });
      const { list, page, total } = await todoService.queryEquipmentByparams({ page: 1, isHomeQueryFlag: true });
      const isMore = list.length < total;
      this.setState(produce(draft => {
        draft.list = list;
        draft.showLoading = false;
        this.page = page;
        draft.isMore = isMore;
        draft.total = total;
        if (list.length > 0) {
          draft.index = 1;
        } else {
          draft.index = 0;
        }
        if (list.length > 0 && list[0].status == 2) {
          draft.showIncidentBadge = true;
        }
      }));
    } catch (error) {
      this.setState({ isError: true, showLoading: false });
    }
  }

  // 刷新时候获取数据
  _onRefresh = () => {
    this.refreshList({ status: 0, title: 1, type: 1 });
  }

  // 初始化的时候获取数据
  _onInitRefresh = () => {
    this.initRefreshList({ status: 0, title: 1, type: 1 });
  }

  // 上拉加载数据
  _onEndReached = () => {
    if (this.state.isMore) {
      this.fetchList({ status: 0, title: 1, type: 1 });
    }
  }

  _onItemClick = (item) => {
    // global.navigation.navigate({ routeName: 'About', params: { id: item._id } });

    const params = {
      fromNavigation: true,
      id: item._id,
      objType: item.objType,
      equipmentCode: item.equipmentCode,
    };
    // alert(JSON.stringify(params));
    global.navigation.navigate({ routeName: 'deviceInfo', params });
  }

  // 列表的item组件
  _renderItem = (item) => (<Item item={item.item} onItemClick={this._onItemClick} />);

  // 列表的分割线
  _renderItemSeparator = () => (
    <View style={{ height: 0.5, backgroundColor: '#EDF5FA' }} />
  )

  // 列表上拉加载的组件
  _renderListFooter = () => (
    (this.state.list.length > 0) && <ListFooter isMore={this.state.isMore} />
  );

  _onScrollStart = (event) => {
    this.startPosition = event.nativeEvent.contentOffset.y;
  }

  _onScrollEnd = (event) => {
    const distance = event.nativeEvent.contentOffset.y - this.startPosition;
    if (distance > 100) {
      if (this._FlatList) {
        if (this.index < this.state.list.length - 1) {
          this.index = this.index + 1;
          this._FlatList.scrollToIndex({ viewPosition: 0, index: this.index });
        }
      }
    } else if (distance < -100) {
      if (this._FlatList) {
        if (this.index > 0) {
          this.index = this.index - 1;
          this._FlatList.scrollToIndex({ viewPosition: 0, index: this.index });
        }
      }
    } else {
      this._FlatList.scrollToIndex({ viewPosition: 0, index: this.index });
    }


    this.setState(produce(draft => {
      if (draft.list.length > 0 && draft.list[this.index] && draft.list[this.index].status == 2) {
        draft.showIncidentBadge = true;
      } else {
        draft.showIncidentBadge = false;
      }
      draft.index = this.index + 1;
    }));
  }

  change = () => {
    // DeviceEventEmitter.emit('changePageIndexEvent', 'incident');
    // eslint-disable-next-line no-unused-expressions
    // this.state.choice === 'all' ? this.setState({ choice: 'attention' }, () => this.refreshPageEvent()) : this.setState({ choice: 'all' }, () => this.refreshPageEvent());
  }

  showTopBar = () => {
    DeviceEventEmitter.emit('showTopBarEvent');
  }

  toQrcode = () => {
    global.navigation.navigate({ routeName: 'Qrcode', params: { flag: 'device' } });
  }

  toSearch = () => {
    DeviceEventEmitter.emit('swiperIncidentPageEvent', -1);
  }

  toAddPage = () => {
    if (this.state.list.length > 0) {
      global.navigation.navigate({ routeName: 'AddIncident', params: { flag: 'device', sbid: this.state.list[this.index]._id, sbmc: this.state.list[this.index].equipmentName, sbbm: this.state.list[this.index].equipmentCode, equipObjType: this.state.list[this.index].objType, maintOrgId: this.state.list[this.index].maintOrgId, maintOrgName: this.state.list[this.index].maintOrgName } });
    } else {
      global.navigation.navigate({ routeName: 'AddIncident', params: { flag: 'add', sbid: '', sbmc: '', sbbm: '', equipObjType: '', maintOrgId: '', maintOrgName: '' } });
    }
  }

  _FlatList;

  render() {
    const {
      showLoading, isError, list, refreshing,
    } = this.state;

    let mView = <Loading />;
    if (!showLoading) {
      if (list.length === 0) {
        mView = <BlankBackground isError={isError} onRefresh={this._onInitRefresh} />;
      } else {
        mView = (
          <FlatList
            ref={(ref) => {
              this._FlatList = ref;
            }}
            renderItem={this._renderItem}
            data={list}
            decelerationRate={0.1}
            keyExtractor={(item, index) => item + index}
            onRefresh={this._onRefresh}
            refreshing={refreshing}
            onEndReachedThreshold={0.05}
            onScrollBeginDrag={this._onScrollStart}
            onScrollEndDrag={this._onScrollEnd}
            scrollEventThrottle={200}
            onEndReached={this._onEndReached}
            ListFooterComponent={this._renderListFooter}
            // ItemSeparatorComponent={this._renderItemSeparator}
          />
        );
      }
    }

    return (
      <View style={styles.container}>
        <View style={styles.header}>
          <View style={{ flex: 1 }}>
            <ZlstIcon
              onPress={this.toSearch}
              name="sousuokuangnei"
              size={22}
              color="white"
              style={{ marginLeft: 20 }}
            />
          </View>
          <TouchableWithoutFeedback
            onPress={this.change}
            style={{ flexDirection: 'row', justifyContent: 'center', alignItems: 'center', flex: 1  }}
          >
            {/* <Image
              resizeMode="contain"
              style={{ width: 160, height: 100 }}
              source={require('../../../../assets/images/asset.png')}
              fadeDuration={0}
            /> */}
            <View style={{ flexDirection: 'row', justifyContent: 'center', alignItems: 'center' }}>
              <Text style={[styles.shadow, { fontSize: this.state.choice === 'all' ? 18 : 16, color: 'white' }]}>设备</Text>
              {/* <Text style={{ color: 'white', fontSize: 18 }}> | </Text>
              <Text style={{ fontSize: this.state.choice === 'attention' ? 18 : 16, color: 'white' }}>关注</Text> */}
            </View>
          </TouchableWithoutFeedback>
          <View style={{ flexDirection: 'row', justifyContent: 'flex-end', alignItems: 'center', flex: 1  }}>
            <ZlstIcon
              onPress={this.toQrcode}
              name="saoma"
              size={22}
              color="white"
              style={{ marginRight: 20 }}
            />
            <Icon
              onPress={this.showTopBar}
              type="MaterialCommunityIcons"
              name="dots-horizontal"
              style={{ marginRight: 10, fontSize: 22, color: 'white' }}
            />
          </View>
        </View>
        <Tab toAddPage={this.toAddPage} />
        <View style={styles.float_pagesize}>
          {/* <Text style={[styles.badge, { backgroundColor: this.state.showIncidentBadge ? 'red' : 'gray' }]} /> */}
          <Text style={{ color: 'white', marginLeft: 5 }}>
            {this.state.index}/{this.state.total}
          </Text>
        </View>
        {mView}
      </View>
    );
  }
}

const styles = StyleSheet.create({
  shadow: {
    textShadowRadius: 2,
    textShadowColor: 'black',
  },
  container: {
    flex: 1,
    width: '100%',
    backgroundColor: Theme.myPrimary,
  },
  header: {
    position: 'absolute',
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    width: '100%',
    height: 65,
    zIndex: 1,
  },
  icon_container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  icon: {
    color: 'white',
    padding: 10,
  },
  badge: {
    height: 10,
    width: 10,
    backgroundColor: 'red',
    borderRadius: 5,
    marginRight: 5,
  },
  float_pagesize: {
    right: 0,
    top: 60,
    position: 'absolute',
    flexDirection: 'row',
    justifyContent: 'center',
    color: 'white',
    alignItems: 'center',
    borderTopLeftRadius: 11,
    borderBottomLeftRadius: 11,
    backgroundColor: 'rgba(255,255,255,0.30)',
    paddingLeft: 5,
    paddingRight: 5,
    height: 22,
    zIndex: 1,
  },
});

export default DevicesList;
